<template>
  <!-- 通知公告 -->
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="queryParams.noticeTitle" placeholder="请输入公告标题" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="操作人员" prop="createByName">
              <el-input v-model="queryParams.createByName" placeholder="请输入操作人员" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="noticeType" style="width: 160px">
              <el-select v-model="queryParams.noticeType" placeholder="请选择" clearable>
                <el-option v-for="dict in sys_notice_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-hasPermi="['system:notice:query']">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:notice:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:notice:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:notice:remove']">
              删除
            </el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange" max-height="550">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" prop="noticeId" v-if="false" />
        <el-table-column label="公告标题" align="center" prop="noticeTitle" :show-overflow-tooltip="true" width="400" />
        <el-table-column label="公告类型" align="center" prop="noticeType">
          <template #default="scope">
            <dict-tag :options="sys_notice_type" :value="scope.row.noticeType" />
          </template>
        </el-table-column>
        <el-table-column label="内容类型" align="center">
          <template #default="scope">
            <span v-if="scope.row.contentType == 'H5'">
              H5
            </span>
            <span v-if="scope.row.contentType == 'H5_LINK'">
              H5_LINK
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_notice_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="创建者" align="center" prop="createByName" width="100" /> -->
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="预览" placement="top">
              <el-button link type="primary" icon="Expand" @click="diosneint(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:notice:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:notice:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="780px" append-to-body v-if="dialog.visible">
      <el-form ref="noticeFormRef" :model="form" :rules="rules" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" clearable maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" placeholder="请选择" clearable>
                <el-option v-for="dict in sys_notice_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内容类型" prop="contentType">
              <el-select v-model="form.contentType" placeholder="请选择" clearable @change="tuonseuio">
                <el-option v-for="dict in guoeuiguon" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable>
                <el-option v-for="dict in sys_notice_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="noticeContent">
              <el-input v-model="form.noticeContent" placeholder="请输入公告内容" clearable
                v-if="form.contentType == 'H5_LINK'" />
              <editor v-model="form.noticeContent" :min-height="192" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.noticeType == '2'">
            <el-form-item label="弹框类型" prop="fillType">
              <el-select v-model="form.fillType" placeholder="请选择" clearable @change="tuionsenh">
                <el-option v-for="dict in tuinseon" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.noticeType == '2'">
            <el-form-item label="只弹一次" prop="boxOnce">
              <el-select v-model="form.boxOnce" placeholder="请选择" clearable>
                <el-option v-for="dict in suoneonti" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.noticeType == '2'">
            <el-form-item label="公告位置" prop="location">
              <el-select v-model="form.location" placeholder="请选择" clearable>
                <el-option v-for="dict in huoinset" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.noticeType == '2'">
            <el-form-item label="弹框内容" prop="fillContent">
              <el-input v-model="form.fillContent" placeholder="请输入弹框内容" type="textarea" clearable v-if="form.fillType == 'TEXT'" />

              <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers"
                :show-file-list="false" :on-success="huonseinau" v-else>
                <img v-if="form.fillContent" :src="form.fillContent" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>

              <!-- <el-upload class="avatar-uploader" action="#" :http-request="upuonsetics" :show-file-list="false" v-else>
                <img v-if="form.fillContent" :src="form.fillContent" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload> -->
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.noticeType == '2'">
            <el-form-item label="开始时间">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="开始时间" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.noticeType == '2'">
            <el-form-item label="截止日期">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.noticeType == '2'">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.noticeType == '2'">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看公告内容弹窗 -->
    <el-dialog :title="tonseuin.title" v-model="tonseuin.visible" width="780px" append-to-body v-if="tonseuin.visible">
      <div v-html="tuinseons?.noticeContent"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="tonseuin.visible = false">确 定</el-button>
          <el-button @click="tonseuin.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Notice" lang="ts">
import upload from "@/utils/upload";
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/system/notice";
import { NoticeForm, NoticeQuery, NoticeVO } from "@/api/system/notice/types";
// 获取toke的方法
import { globalHeaders } from "@/utils/request";
const huonseom = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_notice_status, sys_notice_type } = toRefs<any>(proxy?.useDict("sys_notice_status", "sys_notice_type"));

const noticeList = ref<NoticeVO[]>([]);
const tuinseons = ref<NoticeVO>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const noticeFormRef = ref<ElFormInstance>();

const nonmetime = ref<[DateModelType, DateModelType]>(['', '']);


// 公告添加弹窗的内容类型
const guoeuiguon = ref([
  {
    value: 'H5',
    label: 'H5'
  }, {
    value: 'H5_LINK',
    label: 'H5_LINK'
  }
])

// 公告添加弹窗的内容类型
const tuinseon = ref([
  {
    value: 'IMG',
    label: '图片'
  }, {
    value: 'TEXT',
    label: '文本'
  }
])

// 公告添加弹窗的公告弹框位置
const huoinset = ref([
  {
    value: 'global',
    label: '全局'
  }
])
// 公告添加弹窗的是否只弹框一次
const suoneonti = ref([
  {
    value: 1,
    label: '是'
  },
  {
    value: 0,
    label: '否'
  }
])

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const tonseuin = reactive<DialogOption>({
  visible: false,
  title: '公告详情'
});

const initFormData: NoticeForm = {
  noticeId: undefined,
  noticeTitle: '',
  noticeType: '1',
  noticeContent: '',
  contentType: 'H5',
  sort: 0,
  fillType: 'TEXT',
  fillContent: '',
  location: 'global',
  remark: '',
  status: '1',
  startTime: '',
  endTime: '',
  boxOnce: 1,
}
const data = reactive<PageData<NoticeForm, NoticeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    noticeTitle: '',
    createByName: '',
    status: '',
    noticeType: ''
  },
  rules: {
    noticeTitle: [{ required: true, message: "公告标题不能为空", trigger: "blur" }],
    noticeType: [{ required: true, message: "公告类型不能为空", trigger: "change" }],
    fillContent: [{ required: true, message: "弹框内容不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询公告列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNotice(queryParams.value);
  noticeList.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  noticeFormRef.value?.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: NoticeVO[]) => {
  ids.value = selection.map(item => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 内容类型触发方法清空内容
const tuonseuio = () => {
  form.value.noticeContent = '';
}
// 弹框类型触发方法清空内容
const tuionsenh = () => {
  form.value.fillContent = '';
}
/**
 * 获取图片上传url
 * @param res 
 */
const huonseinau = async (res: any) => {
  if (res.code === 200) {
    form.value.fillContent = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
    // console.log(res.data.url);
  }
}
// 弹框内容图片上传
const upuonsetics: any = (op: any) => {
  // console.log(op);
  upload(op.file).then((res: any) => {
    // console.log(res);
    form.value.fillContent = res;
  });
}
// 列表查看详情
const diosneint = async (row: any) => {
  // console.log(row);
  if (row.contentType == 'H5') {
    const noticeId = row.noticeId
    const { data } = await getNotice(noticeId);
    tuinseons.value = data;
    tonseuin.visible = true;
  } else {
    window.open(row.noticeContent, '_blank');
  }
}
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加公告";
}
/**修改按钮操作 */
const handleUpdate = async (row?: NoticeVO) => {
  reset();
  const noticeId = row?.noticeId || ids.value[0];
  const { data } = await getNotice(noticeId);
  Object.assign(form.value, data);
  dialog.visible = true;
  dialog.title = "修改公告";
}
/** 提交按钮 */
const submitForm = () => {
  noticeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.noticeId ? await updateNotice(form.value) : await addNotice(form.value);
      proxy?.$modal.msgSuccess("添加成功");
      dialog.visible = false;
      await getList();
    }
  });
}
/** 删除按钮操作 */
const handleDelete = async (row?: NoticeVO) => {
  const noticeIds = row?.noticeId || ids.value[0]
  try {
    await proxy?.$modal.confirm('是否确定删除');
    await delNotice(noticeIds);
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  } catch (error) { }
}

onMounted(() => {
  getList();
})
</script>
<style lang="scss" scoped>
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.tonseuoh {
  font-size: 19px;
  font-weight: bold;
  font-family: 楷体;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
